package com.doubletick.proxy.liao;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

@Slf4j
public class SocksTest {
    public static void main(String[] args) {
        String result = getResponseWithHttpProxy("bra.ppfly.xyz", 1081,
                "feng005_c1-res-US-session-74720844-sessTime-5", "feng005",
                "https://api.ipify.org/?format=json");
//                "https://cip.cc");
        log.info(result);
    }

    @SneakyThrows
    private static String getResponseWithHttpProxy(String proxyGate, int proxyPort, String username, String password, String requestUrl) {

        // 创建HttpClient
        try (CloseableHttpClient httpClient = createHttpClientWithSocks5Proxy(proxyGate, proxyPort, username, password)) {
            // 创建一个HttpGet请求
            HttpGet request = new HttpGet(requestUrl);

            // 执行请求并获取响应
            // ...（这里需要处理响应）
            CloseableHttpResponse response = httpClient.execute(request);
            log.info("response: {}", response.getEntity());
            log.info("response: {}", response);
            // 注意：上面的execute方法应该被调用以实际发送请求，但为了示例的简洁性，这里省略了
        }
        return null;
    }

    private static CloseableHttpClient createHttpClientWithSocks5Proxy(String proxyHost, int proxyPort, String proxyUser, String proxyPassword) {
        // 创建连接管理器
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();

        // 创建凭证提供者
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                new AuthScope(proxyHost, proxyPort),
                new UsernamePasswordCredentials(proxyUser, proxyPassword));

        // 创建请求配置
        RequestConfig requestConfig = RequestConfig.custom()
                .setProxy(new HttpHost(proxyHost, proxyPort, "HTTP")) // 设置SOCKS5代理
                .build();

        // 使用Builder构建HttpClient
        return HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .setConnectionManager(cm)
                .setDefaultCredentialsProvider(credsProvider)
                .build();
    }

}
